class Queue {
  constructor () {
    this._list = [];
    this._run = false;
    this._stopped = false;
  }

  add (fn) {
    return new Promise(resolve => {
      this._list.push({ resolve, fn });
      this._trigger();
    });
  }

  clear () {
    this._list = [];
    this._stopped = true;
    return this;
  }

  _trigger () {
    if (!this._run) {
      if (this._list.length > 0) {
        this._run = true;
        let { resolve, fn } = this._list.shift();
        Promise.resolve().then(() => fn()).then(a => {
          this._run = false;
          resolve(a);
          this._trigger();
        }, e => {
          this._run = false;
          console.log(e);
          resolve(e);
          this._trigger();
        });
      } else {
        this._run = false;
      }
    }
  }
}

export default Queue;